﻿namespace Sample
{
	using System;
	using System.Windows;
	using System.Windows.Controls;

	using Ecng.Common;
	using Ecng.ComponentModel;

	using StockSharp.Quik;
	using StockSharp.BusinessEntities;

	public partial class NewStopOrderWindow
	{
		private readonly bool _initialized;

		public NewStopOrderWindow()
		{
			InitializeComponent();
            x_Security.ItemsSource = MainWindow.Instance.Trader.Securities;
            x_Portfolio.ItemsSource = MainWindow.Instance.Trader.Portfolios;
//		Portfolio.Trader = MainWindow.Instance.Trader;
			_initialized = true;
			RefreshControls();
			x_OtherSecurities.ItemsSource = MainWindow.Instance.Trader.Securities;
			x_OtherSecurities.SelectedIndex = 0;
			x_ActiveTimeFrom.Value = new DateTime(new TimeSpan(10, 0, 0).Ticks);
			x_ActiveTimeTo.Value = new DateTime(new TimeSpan(23, 50, 0).Ticks);
			x_Offset.Unit = new Unit();
			x_Spread.Unit = new Unit();
            //Security = x_Security.SelectionBoxItem;
		}

		public Security Security { get; set; }

		private Order _conditionOrder;

		public Order ConditionOrder
		{
			get { return _conditionOrder; }
			set
			{
				if (value == null)
					throw new ArgumentNullException("value");

				_conditionOrder = value;
      //          Security = x_Security.SelectionBoxItem;

				Security = value.Security;


				// типы стоп-заявок "со связанной заявкой" и "по другой бумаге" недоступны при стоп-заявке по исполнению
				x_LinkedOrderType.IsEnabled = OtherSecurityType.IsEnabled = false;

				// заявка условие всегда имеет противоположное направление
				x_IsBuy.IsChecked = (value.Direction == OrderDirections.Buy);

				// пользователь не может выбрать направление завки
				x_IsBuy.IsEnabled = x_IsSell.IsEnabled = false;

				// выбираем по умолчанию тип стоп-лимит
				x_StopOrderType.SelectedIndex = 1;
				
				x_PartiallyMatched.IsEnabled = x_UseMatchedBalance.IsEnabled = true;
				x_PartiallyMatched.IsChecked = x_UseMatchedBalance.IsChecked = true;
			}
		}

		private void SendClick(object sender, RoutedEventArgs e)
		{
			Order stopOrder;

			// если это обычная стоп-заявка
			if (ConditionOrder == null)
			{
				switch (x_StopOrderType.SelectedIndex)
				{
					case 0:
						stopOrder = CreateLinkedOrder();
						break;
					case 1:
						stopOrder = CreateStopLimit();
						break;
					case 2:
						stopOrder = CreateOtherSecurity();
						break;
					case 3:
						stopOrder = CreateTakeProfit();
						break;
					case 4:
						stopOrder = CreateTakeProfitAndStopLimit();
						break;
					default:
						throw new InvalidOperationException("Выбран неизвестный тип стоп-заявки.");
				}
			}
			else // если это стоп-заявка "по исполнению"
			{
				switch (x_StopOrderType.SelectedIndex)
				{
					case 1:
						stopOrder = CreateConditionStopLimit();
						break;
					case 3:
						stopOrder = CreateConditionTakeProfit();
						break;
					case 4:
						stopOrder = CreateConditionTakeProfitAndStopLimit();
						break;
					default:
						throw new InvalidOperationException("Выбран неизвестный тип стоп-заявки.");
				}
			}

		//	stopOrder.Portfolio = Portfolio.SelectedPortfolio;
		    stopOrder.Portfolio = (Portfolio)x_Portfolio.SelectedItem;

			MainWindow.Instance.Trader.RegisterOrder(stopOrder);
			DialogResult = true;
		}

		private Order CreateLinkedOrder()
		{
			return new Order
			{
				Type = OrderTypes.Conditional,
				Volume = x_Volume.Text.To<decimal>(),
				Price = x_Price.Text.To<decimal>(),
				//Security = Security,
                Security = (Security)x_Security.SelectionBoxItem,
				Direction = x_IsBuy.IsChecked == true ? OrderDirections.Buy : OrderDirections.Sell,
				ExpiryDate = x_ExpirationDate.Value,
				StopCondition = new QuikStopCondition
				{
					Type = QuikStopConditionTypes.LinkedOrder,
					LinkedOrderPrice = x_LinkedOrderPrice.Text.To<decimal>(),
					LinkedOrderCancel = x_LinkedOrderCancel.IsChecked == true,
					StopPrice = x_StopPrice.Text.To<decimal>(),
					ActiveTime = ActiveTime,
				},
			};
		}

		private Order CreateStopLimit()
		{
			return new Order
			{
				Type = OrderTypes.Conditional,
				Volume = x_Volume.Text.To<decimal>(),
				Price = x_Price.Text.To<decimal>(),
                //Security = Security,
                Security = (Security)x_Security.SelectionBoxItem,
				Direction = x_IsBuy.IsChecked == true ? OrderDirections.Buy : OrderDirections.Sell,
				ExpiryDate = x_ExpirationDate.Value,
				StopCondition = new QuikStopCondition
				{
					Type = QuikStopConditionTypes.StopLimit,
					StopPrice = x_StopPrice.Text.To<decimal>(),
					ActiveTime = ActiveTime,
				},
			};
		}

		private Order CreateOtherSecurity()
		{
			return new Order
			{
				Type = OrderTypes.Conditional,
				Volume = x_Volume.Text.To<decimal>(),
				Price = x_Price.Text.To<decimal>(),
                //Security = Security,
                Security = (Security)x_Security.SelectionBoxItem,
				Direction = x_IsBuy.IsChecked == true ? OrderDirections.Buy : OrderDirections.Sell,
				ExpiryDate = x_ExpirationDate.Value,
				StopCondition = new QuikStopCondition
				{
					Type = QuikStopConditionTypes.OtherSecurity,
					StopPriceCondition = x_StopPriceCondition.Text == ">=" ? QuikStopPriceConditions.MoreOrEqual : QuikStopPriceConditions.LessOrEqual,
					StopPrice = x_StopPrice.Text.To<decimal>(),
					OtherSecurity = (Security)x_OtherSecurities.SelectedValue,
					ActiveTime = ActiveTime,
				},
			};
		}

		private Order CreateTakeProfit()
		{
			return new Order
			{
				Type = OrderTypes.Conditional,
				Volume = x_Volume.Text.To<decimal>(),
                //Security = Security,
                Security = (Security)x_Security.SelectionBoxItem,
				Direction = x_IsBuy.IsChecked == true ? OrderDirections.Buy : OrderDirections.Sell,
				ExpiryDate = x_ExpirationDate.Value,
				StopCondition = new QuikStopCondition
				{
					Type = QuikStopConditionTypes.TakeProfit,
					StopPrice = x_StopPrice.Text.To<decimal>(),
					Offset = x_Offset.Unit,
					Spread = x_Spread.Unit,
					ActiveTime = ActiveTime,
				},
			};
		}

		private Order CreateTakeProfitAndStopLimit()
		{
			return new Order
			{
				Type = OrderTypes.Conditional,
				Volume = x_Volume.Text.To<decimal>(),
				Price = x_Price.Text.To<decimal>(),
                //Security = Security,
                Security = (Security)x_Security.SelectionBoxItem,
				Direction = x_IsBuy.IsChecked == true ? OrderDirections.Buy : OrderDirections.Sell,
				ExpiryDate = x_ExpirationDate.Value,
				StopCondition = new QuikStopCondition
				{
					Type = QuikStopConditionTypes.TakeProfitStopLimit,
					StopPrice = x_StopPrice.Text.To<decimal>(),
					StopLimitPrice = x_StopLimitPrice.Text.To<decimal>(),
					Offset = x_Offset.Unit,
					Spread = x_Spread.Unit,
					ActiveTime = ActiveTime,
				},
			};
		}

		private Order CreateConditionStopLimit()
		{
			var stopLimit = CreateStopLimit();
			var condition = (QuikStopCondition)stopLimit.StopCondition;
			condition.ConditionOrder = ConditionOrder;
			condition.ConditionOrderPartiallyMatched = x_PartiallyMatched.IsChecked;
			condition.ConditionOrderUseMatchedBalance = x_UseMatchedBalance.IsChecked;
			return stopLimit;
		}

		private Order CreateConditionTakeProfit()
		{
			var stopLimit = CreateTakeProfit();
			var condition = (QuikStopCondition)stopLimit.StopCondition;
			condition.ConditionOrder = ConditionOrder;
			condition.ConditionOrderPartiallyMatched = x_PartiallyMatched.IsChecked;
			condition.ConditionOrderUseMatchedBalance = x_UseMatchedBalance.IsChecked;
			return stopLimit;
		}

		private Order CreateConditionTakeProfitAndStopLimit()
		{
			var stopLimit = CreateTakeProfitAndStopLimit();
			var condition = (QuikStopCondition)stopLimit.StopCondition;
			condition.ConditionOrder = ConditionOrder;
			condition.ConditionOrderPartiallyMatched = x_PartiallyMatched.IsChecked;
			condition.ConditionOrderUseMatchedBalance = x_UseMatchedBalance.IsChecked;
			return stopLimit;
		}

		private void StopOrderTypeSelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			RefreshControls();
		}

		private void RefreshControls()
		{
			if (_initialized)
			{
				x_LinkedOrderCancel.IsEnabled = x_LinkedOrderPrice.IsEnabled = x_StopOrderType.SelectedIndex == 0;
				x_StopPriceCondition.IsEnabled = x_OtherSecurities.IsEnabled = x_StopOrderType.SelectedIndex == 2;
				x_Offset.IsUnitEnabled = x_Spread.IsUnitEnabled = x_StopOrderType.SelectedIndex == 3 || x_StopOrderType.SelectedIndex == 4;
				x_Price.IsEnabled = x_StopOrderType.SelectedIndex != 3;
				x_StopLimitPrice.IsEnabled = x_StopOrderType.SelectedIndex == 4;
			}
		}

		private Range<DateTime> ActiveTime
		{
			get
			{
				if (x_IsActiveTime.IsChecked == true)
					return new Range<DateTime>(DateTime.Today + x_ActiveTimeFrom.Value.Value.TimeOfDay, DateTime.Today + x_ActiveTimeTo.Value.Value.TimeOfDay);
				else
					return null;
			}
		}

		private void IsActiveTimeChecked(object sender, RoutedEventArgs e)
		{
			x_ActiveTimeFrom.IsEnabled = x_ActiveTimeTo.IsEnabled = x_IsActiveTime.IsChecked == true;
		}
	}
}